import express from 'express'
import cors from 'cors'
import dotenv from 'dotenv'
import fs from 'fs'
import routes from './routes/index.js'
import { errorHandler, errorLogger } from './middlewares/error.js'
import { requestLogger } from './middlewares/monitor.js'
import logger from './services/logger.js'
import { config } from './config/index.js'
import { vectorStore } from './services/vectorStore.js'
import { modelService } from './services/model.js'
import { documentService } from './services/document.js'

// 设置默认编码
process.env.LANG = 'en_US.UTF-8'
process.env.LC_ALL = 'en_US.UTF-8'

// 加载环境变量
dotenv.config()

const app = express()
const port = config.server.port

// 中间件
app.use(cors({
  origin: ['http://localhost:5173'],
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  exposedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 86400 // 缓存 CORS 配置 24 小时
}))

app.use(express.json({ charset: 'utf-8', limit: '50mb' }))
app.use(express.urlencoded({ extended: true, charset: 'utf-8', limit: '50mb' }))
app.use(requestLogger)

// 添加全局响应头
app.use((req, res, next) => {
  res.setHeader('Connection', 'keep-alive')
  res.setTimeout(600000, () => {
    logger.warn('Request timeout:', {
      method: req.method,
      url: req.url,
      ip: req.ip
    })
  })
  next()
})

// 添加调试中间件
app.use((req, res, next) => {
  res.setHeader('Access-Control-Allow-Origin', 'http://localhost:5173')
  res.setHeader('Access-Control-Allow-Credentials', 'true')
  logger.info(`Incoming request: ${req.method} ${req.originalUrl}`)
  res.setHeader('Content-Type', 'application/json; charset=utf-8')
  next()
})

// 路由
app.use(routes)

// 404 处理
app.use((req, res) => {
  logger.warn(`404 Not Found: ${req.method} ${req.originalUrl}`)
  res.status(404).json({ message: 'Not Found' })
})

// 错误处理
app.use(errorLogger)
app.use(errorHandler)

// 添加定期健康检查
setInterval(async () => {
  try {
    await vectorStore.client.listCollections()
  } catch (error) {
    logger.error('Milvus health check failed:', error)
    // 尝试重新初始化
    try {
      await vectorStore.reconnect()
    } catch (reconnectError) {
      logger.error('Failed to reconnect to Milvus:', reconnectError)
    }
  }
}, 30000)

try {
  // 1. 确保上传目录存在
  if (!fs.existsSync(config.server.upload.dir)) {
    fs.mkdirSync(config.server.upload.dir, { recursive: true })
  }

  // 2. 初始化模型服务
  await modelService.init()
  logger.info('Model service initialized')

  // 3. 初始化向量存储
  await vectorStore.init()
  logger.info('Vector store initialized')

  // 4. 初始化文档服务
  await documentService.init()
  logger.info('Document service initialized')

  // 6. 启动服务器
  app.listen(port, () => {
    logger.info(`Server running on port ${port}`)
  })
} catch (error) {
  logger.error('Failed to start server:', error)
  process.exit(1)
}

export default app